package cn.exrick.sso.service.impl;

import java.util.Date;
import java.util.List;


import cn.exrick.common.constant.CommonConstant;
import cn.exrick.common.exception.XmallException;
import cn.exrick.common.pojo.Result;
import cn.exrick.common.utils.ResultUtil;
import cn.exrick.manager.dto.front.MemberLoginRegist;
import cn.exrick.manager.mapper.TbMemberMapper;
import cn.exrick.manager.pojo.TbMember;
import cn.exrick.manager.pojo.TbMemberExample;
import cn.exrick.sso.service.RegisterService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


@Service
public class RegisterServiceImpl implements RegisterService {
	
	@Autowired
	private TbMemberMapper tbMemberMapper;

	@Override
	public boolean checkData(String param, int type,Long memberId) {

		TbMemberExample example = new TbMemberExample();
		TbMemberExample.Criteria criteria = example.createCriteria();
		criteria.andStatusEqualTo(CommonConstant.ACCOUNT_STATUS_NORMAL);
		if(memberId != null){
			criteria.andIdNotEqualTo(memberId);
		}
		//1：用户名 2：手机号 3：邮箱
		if (type == 1) {
			criteria.andUsernameEqualTo(param);
		} else if (type == 2) {
			criteria.andPhoneEqualTo(param);
		} else if (type == 3) {
			criteria.andEmailEqualTo(param);
		} else {
			return false;
		}

		List<TbMember> list = tbMemberMapper.selectByExample(example);
		if (list != null && list.size()>0) {
			return false;
		}
		return true;
	}

	@Override
	public Result<Object> register(MemberLoginRegist memberLoginRegist) {

		String userName = memberLoginRegist.getUserName();
		String userPwd = memberLoginRegist.getUserPwd();
		String email = memberLoginRegist.getEmail();
		String phone = memberLoginRegist.getPhone();
		TbMember tbMember=new TbMember();
		tbMember.setUsername(userName);

		if(StringUtils.isBlank(userName) || StringUtils.isBlank(userPwd)){
			return new ResultUtil<>().setErrorMsg("用户名或密码不能为空");
		}
		boolean userNameResult = checkData(userName, 1,null);
		if (!userNameResult) {
			return new ResultUtil<>().setErrorMsg("该用户名已被注册");
		}

		boolean phoneResult = checkData(phone, 2,null);
		if (!phoneResult) {
			return new ResultUtil<>().setErrorMsg("该手机号已被注册");
		}

		boolean emailResult = checkData(email, 3,null);
		if (!emailResult) {
			return new ResultUtil<>().setErrorMsg("该邮箱已被注册");
		}

		//MD5加密
		String md5Pass = DigestUtils.md5DigestAsHex(userPwd.getBytes());
		tbMember.setPassword(md5Pass);
		tbMember.setStatus(CommonConstant.ACCOUNT_STATUS_NORMAL);
		tbMember.setType(CommonConstant.MEMBER_TYPE_OUT);
		tbMember.setEmail(memberLoginRegist.getEmail());
		tbMember.setPhone(memberLoginRegist.getPhone());
		tbMember.setCreateTime(new Date());
		tbMember.setUpdateTime(new Date());

		if(tbMemberMapper.insert(tbMember)!=1){
			throw new XmallException("注册用户失败");
		}
		return new ResultUtil<>().setData(null);
	}

	

}
